#pragma execution_character_set("utf-8")
#include "stdafx.h"
#include "delegate.h"
#include <QComboBox>
 
/////////////////////////////////////////////////////////////
// ComboBoxDelegate

ComboBoxDelegate::ComboBoxDelegate(QObject *parent)
    : QStyledItemDelegate(parent)
{
}
 
ComboBoxDelegate::~ComboBoxDelegate()
{
}
 
QWidget *ComboBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option,
                                                   const QModelIndex &index) const
{
    if (index.isValid())
    {
        QComboBox *editor = new QComboBox(parent);
        editor->setEditable(true);
        editor->installEventFilter(const_cast<ComboBoxDelegate *>(this));
        return editor;
    }
    else
    {
        return QStyledItemDelegate::createEditor(parent, option, index);
    }
}
 
void ComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    if (index.isValid())
    {
        QString value = index.model()->data(index, Qt::DisplayRole).toString();
        QComboBox *combox = dynamic_cast<QComboBox *>(editor);
        combox->addItem("0");
        combox->addItem("1");
        combox->setCurrentText(value);
    }
    else
    {
        QStyledItemDelegate::setEditorData(editor, index);
    }
}
 
void ComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                             const QModelIndex &index) const
{
    if (index.isValid())
    {
        QComboBox *combox = dynamic_cast<QComboBox *>(editor);
        model->setData(index, combox->currentText());
    }
    else
    {
        QStyledItemDelegate::setModelData(editor, model, index);
    }
}

/////////////////////////////////////////////////////////////
// SpinBoxDelegate

SpinBoxDelegate::SpinBoxDelegate(QObject *parent)
    : QStyledItemDelegate(parent)
{
}

QWidget *SpinBoxDelegate::createEditor(QWidget *parent,
    const QStyleOptionViewItem &/* option */,
    const QModelIndex &/* index */) const
{
    QSpinBox *editor = new QSpinBox(parent);
    editor->setFrame(false);
    editor->setMinimum(-10);
    editor->setMaximum(10);

    return editor;
}

void SpinBoxDelegate::setEditorData(QWidget *editor,
                                    const QModelIndex &index) const
{
    int value = index.model()->data(index, Qt::EditRole).toInt();

    QSpinBox *spinBox = static_cast<QSpinBox*>(editor);
    spinBox->setValue(value);
}

void SpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                   const QModelIndex &index) const
{
    QSpinBox *spinBox = static_cast<QSpinBox*>(editor);
    spinBox->interpretText();
    int value = spinBox->value();

    model->setData(index, value, Qt::EditRole);
}

void SpinBoxDelegate::updateEditorGeometry(QWidget *editor,
    const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
{
    editor->setGeometry(option.rect);
}
